package com.yangyang.textscope;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    private static final String SAVED_TEXT_KEY = "saved_text";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
//        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
//            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
//            return insets;
//        });

        // 设置标题为空
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("");
        }

        textView = findViewById(R.id.textView);


        // 恢复保存的文本（如果有）
        if (savedInstanceState != null) {
            String string = savedInstanceState.getString(SAVED_TEXT_KEY);
            textView.setText(string);
        }
    }


    //加载菜单资源
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    //以响应菜单项的选择。
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.menu_copy) {
            // 复制
            CharSequence text = textView.getText();
            ClipboardHelper.setClipboardText(this, text.toString());
            return true;
        }
        if (id == R.id.menu_paste) {
            // 粘贴
            String clipboardText = ClipboardHelper.getClipboardText(this);
            if (TextUtils.isEmpty(clipboardText)) {
                Toast.makeText(this, "剪切板内容为空", Toast.LENGTH_SHORT).show();
            } else {
                textView.setText(clipboardText);
            }
            return true;
        }

        if (id == R.id.menu_delete) {
            // 清空
            textView.setText("");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存当前文本
        outState.putString(SAVED_TEXT_KEY, textView.getText().toString());
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // 恢复文本
        String dataText = savedInstanceState.getString(SAVED_TEXT_KEY);
        textView.setText(dataText);
    }
}